<template>
  <div class="checked-box">
    <template v-for="item in modelValue" :key="item.id">
      <ttCheckbox
        v-model="item.checked"
        :type="multiple ? 'rect' : 'circle'"
        :readonly="!multiple"
        @checkClick="checkClick($event, item)"
        >{{ item.label }}</ttCheckbox
      >
    </template>
  </div>
</template>
<script setup>
import ttCheckbox from "@/components/tt/tt-checkbox.vue";
import $common from "@/utils/$common";

const props = defineProps({
  modelValue: {
    default: () => {
      return [];
    },
  },
  //是否根据id大小进行排序
  idSort: {
    default: true,
  },
  multiple: {
    default: true,
  },
});
const emits = defineEmits(["update:modelValue"]);

function checkClick(status, item) {
  if (props.multiple) {
    return;
  }
  props.modelValue.forEach((self) => {
    self.checked = false;
  });
  item.checked = true;
  emits("update:modelValue", props.modelValue);
}

//获取选中的id
function getCheckId() {
  let arr = $common.deepCopy(props.modelValue);
  if (props.idSort) {
    arr.sort((a, b) => {
      return a.id - b.id;
    });
  }

  let list = [];
  arr.forEach((item) => {
    if (item.checked) {
      list.push(item.id);
    }
  });

  return list.join(",");
}

//获取选中的label
function getCheckLabel() {
  let arr = $common.deepCopy(props.modelValue);

  if (props.idSort) {
    arr.sort((a, b) => {
      return a.id - b.id;
    });
  }

  let list = [];
  arr.forEach((item) => {
    if (item.checked) {
      list.push(item.label);
    }
  });

  return list.join(",");
}

defineExpose({
  getCheckId,
  getCheckLabel,
});
</script>
<style lang="scss" scoped>
.checked-box {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
</style>
